package com.util;

import com.github.pagehelper.PageInfo;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 对雨MyBatis 的resultmap分页不对
 * 或者一对多的查询进行分页
 */
public class PageInfoUtil {

    public static <T> PageInfo<T> listToPageInfo(List<T> list, Integer pageNum, Integer pageSize) {
        pageNum = null == pageNum ? 1 : pageNum;
        pageSize = null == pageSize ? 10 : pageSize;
        if (pageNum <= 0) {
            pageNum = 1;
        }
        int pageNo = (pageNum - 1) * pageSize;
        int total = 0;
        int pages = 0;
        PageInfo<T> pageInfo = null;
        if (!CollectionUtils.isEmpty(list)) {
            total = list.size();
            pages = (total / pageSize) + (total % pageSize == 0 ? 0 : 1);
            if (pageNo + pageSize > total) {
                if (pageNo > total) {
                    list = new ArrayList<>();
                } else {
                    list = list.subList(pageNo, total);
                }
            } else {
                list = list.subList(pageNo, (pageNo + pageSize));
            }
            pageInfo = new PageInfo<T>(list);
        } else {
            pageInfo = new PageInfo<T>(new ArrayList<>());
        }
        pageInfo.setPageNum(pageNum);
        pageInfo.setPageSize(pageSize);
        pageInfo.setTotal(total);
        pageInfo.setPages(pages);
        pageInfo.setPrePage(pageNum - 1);
        pageInfo.setNextPage(pageNum + 1);
        pageInfo.setIsFirstPage(pageNum == 1);
        pageInfo.setIsLastPage(pageNum >= pages);
        pageInfo.setHasPreviousPage(pageNum != 1);
        pageInfo.setHasNextPage(pageNum < pages);
        pageInfo.setNavigateFirstPage(1);
        pageInfo.setNavigateLastPage(pages);
        int[] nums = new int[pages];
        for (int i = 0; i < pages; i++) {
            nums[i] = i + 1;
        }
        pageInfo.setNavigatepageNums(nums);
        return pageInfo;
    }
}
